from mcp.server.fastmcp import FastMCP
from typing import Union
import logging

# 创建MCP服务
mcp = FastMCP("Calculator Server")
logger = logging.getLogger(__name__)

@mcp.tool()
def add(a: Union[int, float], b: Union[int, float]) -> Union[int, float]:
    """加法运算"""
    try:
        result = a + b
        logger.info(f"加法运算: {a} + {b} = {result}")
        return result
    except Exception as e:
        logger.error(f"加法运算错误: {e}")
        return f"错误: {e}"

@mcp.tool()
def subtract(a: Union[int, float], b: Union[int, float]) -> Union[int, float]:
    """减法运算"""
    try:
        result = a - b
        logger.info(f"减法运算: {a} - {b} = {result}")
        return result
    except Exception as e:
        logger.error(f"减法运算错误: {e}")
        return f"错误: {e}"

@mcp.tool()
def multiply(a: Union[int, float], b: Union[int, float]) -> Union[int, float]:
    """乘法运算"""
    try:
        result = a * b
        logger.info(f"乘法运算: {a} * {b} = {result}")
        return result
    except Exception as e:
        logger.error(f"乘法运算错误: {e}")
        return f"错误: {e}"

@mcp.tool()
def divide(a: Union[int, float], b: Union[int, float]) -> Union[int, float]:
    """除法运算"""
    try:
        if b == 0:
            raise ValueError("除数不能为零")
        result = a / b
        logger.info(f"除法运算: {a} / {b} = {result}")
        return result
    except Exception as e:
        logger.error(f"除法运算错误: {e}")
        return f"错误: {str(e)}"

if __name__ == "__main__":
    mcp.run(transport="stdio")